package cn.xdf.service;

import cn.xdf.entity.Goods;
import org.apache.solr.client.solrj.SolrQuery;
import org.apache.solr.client.solrj.SolrServerException;
import org.apache.solr.client.solrj.impl.HttpSolrServer;
import org.apache.solr.client.solrj.response.QueryResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.GetMapping;

import java.util.List;
import java.util.Map;

@Service
public class GoodsService {

    @Autowired
    public HttpSolrServer httpSolrServer;


    public List<Goods> search(String searchVal) {

        try {
            //搜索条件
            SolrQuery solrQuery=new SolrQuery("title"+searchVal);


            solrQuery.setHighlight(true);
            solrQuery.addHighlightField("name");
            solrQuery.addHighlightField("title");
            solrQuery.setHighlightSimplePre("<font color='red'>");
            solrQuery.setHighlightSimplePost("</font>");

            QueryResponse response = httpSolrServer.query(solrQuery);

            List<Goods> goodsList = response.getBeans(Goods.class);

            //高亮数据
            Map<String, Map<String, List<String>>> highlighting = response.getHighlighting();

            for(Goods goods:goodsList){
                //获取这个文档的高亮数据
                Map<String, List<String>> high = highlighting.get(goods.getId());

                List<String> name = high.get("name");
                List<String> title = high.get("title");

                if(name!=null){
                    //使用高亮数据替换原始数据
                    goods.setName(name.get(0));
                }
                if(title!=null){
                    //使用高亮数据替换原始数据
                    goods.setTitle(title.get(0));
                }



            }


            return goodsList;
        } catch (SolrServerException e) {
            throw new RuntimeException(e);
        }
    }
}
